import { useUserStore } from '@/stores/user'
import axios, { type Method } from 'axios'

const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/tj',
  timeout: 5000,
})

//后端返回值类型
export interface ServiceResponse<T> {
  code: number
  msg: string
  data: T
}
//封装axios工具函数
export const  request=<T>(url:string,method:Method='GET',submitData?:object)=>{
  return service.request<T,ServiceResponse<T>>({
    url: url,
    method:method,
    [method.toLowerCase()==='GET'?'params':'data']:submitData
  })
}
// 请求拦截器
service.interceptors.request.use(
  config => {
    // 获取token
    const store=useUserStore()
    // 在请求头中添加token
    if(store.token){
      config.headers.Authorization=`Bearer ${store.token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  },
)

service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    return Promise.reject(error)
  },
)

export default service
